<?php

namespace App\Admin\Controllers;

use App\Admin\Traits\tabMenu;
use App\Models\Department;
use App\Models\User;
use Encore\Admin\Auth\Database\Role;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Encore\Admin\Tree;

class UserController extends BaseController
{
    /**
     * {@inheritdoc}
     */
    protected function title()
    {
        return trans('admin.administrator');
    }

    protected $status = [1=>'启用','停用'];
    protected $isBoss = [1=>'是','否'];


    public function index(Content $content)
    {
        $content
            ->title('用户管理')
            ->row(function ($row){
                $row->column(4, $this->department_grid());
                $row->column(8, $this->grid());
            });
        return $content;
    }

    protected function department_grid(){
        return $this->treeView()->render();
    }

    protected function treeView()
    {
        $tree = new Tree(new Department());

        $tree->query(function ($model){
            return $model->with('employees');
        });
        $users = User::Users();
        $tree->branch(function ($branch) use ($users) {
            $ids = self::SumEmployees([$branch['id']]);
            User::query()->whereIn('department_id',$ids)->count();
            $count = User::query()->whereIn('department_id',$ids)->count();
            // empty($branch['employees']) ? 0 : count($branch['employees']);
            if($branch['leader'] == 1){
                $leader = '';
            }else{
                $leader = empty($branch['leader']) ? '' : $users[$branch['leader']];
            }

            $employees = empty($branch['employees']) ? '' : join(', ',collect($branch['employees'])->pluck('name')->toArray());
            $payload = "&nbsp;<strong>{$branch['title']}  &nbsp;&nbsp;( {$count} 人)  </strong>";
            $payload .= "<small style='color: grey'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;主管： $leader</small>";
//            $payload .= "<small style='color: grey'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;组员： $employees</small>";
            return $payload;
        });
//        $tree->tools(function (Tree\Tools $tools){
//            $tools->add('<a class="btn btn-sm btn-success" href="/admin/department/create">新增</a>');
//            $tools->add('<a class="btn btn-sm btn-success" href="/admin/department/create">刷新</a>');
//            $tools->add('<a class="btn btn-sm btn-success" href="/admin/department/create">保存</a>');
//        });

//        $tree->disableCreate();
//        $tree->disableRefresh();
//        $tree->disableSave();
        return $tree;
    }

    /**
     * 获取当前部门下的所有部门ID
     * @param array $ids
     * @return array|\Illuminate\Support\Collection
     */
    public function SumEmployees($ids=[])
    {
        $query = Department::query()->whereIn('parent_id',$ids);
        if($query->count() > 0){
            $ids = $query->pluck('id');
            return $ids->concat(self::SumEmployees($ids));
        }
        return $ids;
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {

        $grid = new Grid(new User());
        $users = User::Users();
        $grid->model()->where('id','>',1)->with('departments');
        $grid->model()->orderBy('created_at', 'desc');
        $grid->column('id', 'ID')->sortable();
        $grid->column('username', trans('admin.username'));
        $grid->column('mobile', trans('admin.mobile'));
        $grid->column('name', trans('admin.name'))->editable();

//        $grid->column('department_id','所属部门')->editable('select',Department::allDepartment());
        $grid->column('dep_l1','所属一级部门')->editable('select',Department::getLevel(1));
        $grid->column('dep_l2','所属二级部门')->editable('select',Department::getLevel(2));
        $grid->column('dep_l3','所属三级部门')->editable('select',Department::getLevel(3));
        $grid->column('is_leader','是否主管')->using([1=>'是']);
        $grid->column('department_boss','直属上级')->display(function ($model){
            return Department::getLeader($this->id);
        });
        $grid->column('roles', trans('admin.roles'))->pluck('name')->label();
        $grid->column('status','状态')->editable('select',$this->status);
        $grid->column('created_at', trans('admin.created_at'));

        $grid->filter(function (Grid\Filter $filter){
            $filter->disableIdFilter();
            $filter->expand();
            $filter->column(1/2,function ($filter) {
                $filter->equal('username', '账号')->select(User::Users());
                $filter->equal('dep_l1','所在一级部门')->select(Department::getLevel(1));
                $filter->equal('dep_l2','所在二级部门')->select(Department::getLevel(2));
                $filter->equal('dep_l3','所在三级部门')->select(Department::getLevel(3));
            });
            $filter->column(1/2,function ($filter) {
                $filter->equal('department_id', '所在部门')->select(Department::allDepartment());
                $filter->equal('is_leader', '是否主管')->select([1=>"是",2=>'否']);
                $filter->equal('name', '用户姓名');
                $filter->equal('roles.id', '角色')->select(Role::all()->pluck('name', 'id')->toArray());
            });
        });

        $grid->disableRowSelector();
        $grid->disableExport();
        $grid->disableColumnSelector();

        $grid->actions(function (Grid\Displayers\Actions $actions) {
            if ($actions->getKey() == 1) {
                $actions->disableDelete();
            }
        });

        $grid->tools(function (Grid\Tools $tools) {
            $tools->batch(function (Grid\Tools\BatchActions $actions) {
                $actions->disableDelete();
            });
        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        $userModel = config('admin.database.users_model');

        $show = new Show($userModel::findOrFail($id));

        $show->field('id', 'ID');
        $show->field('username', trans('admin.username'));
        $show->field('name', trans('admin.name'));
        $show->field('roles', trans('admin.roles'))->as(function ($roles) {
            return $roles->pluck('name');
        })->label();
//        $show->field('permissions', trans('admin.permissions'))->as(function ($permission) {
//            return $permission->pluck('name');
//        })->label();
        $show->field('created_at', trans('admin.created_at'));
        $show->field('updated_at', trans('admin.updated_at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    public function form()
    {
        $userModel = config('admin.database.users_model');
        $permissionModel = config('admin.database.permissions_model');
        $roleModel = config('admin.database.roles_model');

        $form = new Form(new $userModel());

        $userTable = config('admin.database.users_table');
        $connection = config('admin.database.connection');

        $form->display('id', 'ID');
        $form->text('username', trans('admin.username'))
            ->creationRules(['required', "unique:{$connection}.{$userTable}"])
            ->updateRules(['required', "unique:{$connection}.{$userTable},username,{{id}}"]);

        $form->text('name', trans('admin.name'))->rules('required');
        $form->text('mobile', trans('admin.mobile'));
        $form->image('avatar', trans('admin.avatar'));
        $form->password('password', trans('admin.password'))->rules('required|confirmed');
        $form->password('password_confirmation', trans('admin.password_confirmation'))->rules('required')
            ->default(function ($form) {
                return $form->model()->password;
            });

        $form->ignore(['password_confirmation']);

        $form->multipleSelect('roles', trans('admin.roles'))->options($roleModel::query()->where('id','>',1)->pluck('name', 'id'))->required();
//        $form->multipleSelect('permissions', trans('admin.permissions'))->options($permissionModel::all()->pluck('name', 'id'));

        $form->select('department_id',trans('admin.department_id'))->options(Department::allDepartment())->required()->help('必选项，确定在哪一层部门');
        $form->select('dep_l1','所属一级部门')->options(Department::getLevel(1));
        $form->select('dep_l2','所属二级部门')->options(Department::getLevel(2));
        $form->select('dep_l3','所属三级部门')->options(Department::getLevel(3));

        $form->select('status',trans('admin.status'))->options($this->status)->required();

        $form->display('created_at', trans('admin.created_at'));
        $form->display('updated_at', trans('admin.updated_at'));

        $form->saving(function (Form $form) {
            if ($form->password && $form->model()->password != $form->password) {
                $form->password = bcrypt($form->password);
            }
        });

        return $form;
    }
}
